package com.ybkj.daijia.server.controller;

import static com.ybkj.daijia.CommonCons.SUCCESS;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.AppUpdateInfo;
import com.ybkj.daijia.server.model.AppVersion;
import com.ybkj.daijia.server.model.AppVersion.AppVersionType;
import com.ybkj.daijia.server.service.AppUpdateVersionService;
import com.ybkj.daijia.server.service.AppVersionService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "appversion")
public class AppVersionController {

    @Autowired
    private AppVersionService appVersionService;

    @Autowired
    private AppUpdateVersionService appUpdateVersionService;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("appversion/list");

            mv.addObject("content", appVersionService.queryAll());
            mv.addObject("updateContent", appUpdateVersionService.queryAllUpdateInfo());

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "addUpdateInfoPage", method = RequestMethod.GET)
    public ModelAndView addUpdateInfoPage() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("appversion/addUpdateInfo");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "edit/{type}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("type") AppVersionType type) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {
            ModelAndView mv = new ModelAndView();

            AppVersion appVersion = appVersionService.findByAppVersionType(type);

            mv.addObject("appVersion", appVersion);

            mv.setViewName("appversion/edit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "editUpdateInfo/{id}", method = RequestMethod.GET)
    public ModelAndView editUpdateInfo(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {
            ModelAndView mv = new ModelAndView();

            AppUpdateInfo appUpdateInfo = appUpdateVersionService.findById(id);

            mv.addObject("appUpdateInfo", appUpdateInfo);

            mv.setViewName("appversion/modifyUpdateInfo");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(AppVersion appVersion, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("appversion")) {

            AppVersion dbappVersion = appVersionService
                .findByAppVersionType(appVersion.getAppVersionType());
            dbappVersion.setShortversion(appVersion.getShortversion());
            dbappVersion.setBuildversion(appVersion.getBuildversion());
            dbappVersion.setMandatory(appVersion.getMandatory());
            dbappVersion.setAppsize(appVersion.getAppsize());
            dbappVersion.setTitle(appVersion.getTitle());
            dbappVersion.setNotes(appVersion.getNotes());
            dbappVersion.setDownloadurl(appVersion.getDownloadurl());

            appVersionService.updateByPrimaryKey(dbappVersion);

            String detail =
                "【%s】修改了版本设置【" + dbappVersion.getTitle() + "-" +
                    "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "modifyUpdateInfo", method = RequestMethod.POST)
    public String modifyUpdateInfo(
        @RequestParam(required = true, value = "id") String id,
        @RequestParam(required = true, value = "appType") String appType,
        @RequestParam(required = true, value = "version") String version,
        @RequestParam(required = true, value = "onlineTime") String onlineTime,
        @RequestParam(required = true, value = "size") String size,
        @RequestParam(required = true, value = "md5Code") String md5Code,
        @RequestParam(required = true, value = "serverInfo") String serverInfo,
        @RequestParam(required = true, value = "instructions") String instructions
    ) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {

            AppUpdateInfo appUpdateInfo = new AppUpdateInfo();
            appUpdateInfo.setId(Long.valueOf(id));
            appUpdateInfo.setAppType(Integer.valueOf(appType));
            appUpdateInfo.setVersion(version);
            try {
                appUpdateInfo.setOnlineTime(DateUtils.parseDate(onlineTime, "yyyy-MM-dd"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            appUpdateInfo.setSize(Integer.valueOf(size));
            appUpdateInfo.setMd5Code(md5Code);
            appUpdateInfo.setServerInfo(serverInfo);
            appUpdateInfo.setInstructions(instructions);

            appUpdateVersionService.modifyUpdateInfo(appUpdateInfo);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteUpdateInfo/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> deleteUpdateInfo(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("appversion")) {

            Map<String, Object> map = new HashMap<String, Object>();
            try {
                appUpdateVersionService.deleteUpdateInfo(id);
                map.put("success", true);
            } catch (Exception e) {
                map.put("success", false);
            }
            return map;
        } else {
            throw new NoPermissionException();
        }

    }

    @ResponseBody
    @RequestMapping("getLastesdVersion")
    public Map getLastesdVersion(String param) {
        Map<String, Object> map = new HashMap<>();
        boolean success = false;
        if (StringUtils.isNotBlank(param)) {
            AppVersion version = null;
            switch (param) {
                case "androidcustomer":
                    version = appVersionService
                        .findByAppVersionType(AppVersion.AppVersionType.androidcustomer);
                    break;
                case "androiddriver":
                    version = appVersionService
                        .findByAppVersionType(AppVersion.AppVersionType.androiddriver);
                    break;
                case "ioscustomer":
                    version = appVersionService
                        .findByAppVersionType(AppVersion.AppVersionType.ioscustomer);
                    break;
                case "iosdriver":
                    version = appVersionService
                        .findByAppVersionType(AppVersion.AppVersionType.iosdriver);
                    break;

            }
            if (null != version) {
                Map data = new HashMap<String, Object>();
                data.put("code", version.getBuildversion());
                data.put("size", version.getAppsize());
                data.put("msg", version.getNotes());
                data.put("hasNew", true);
                data.put("updateInfo", version.getTitle());
                data.put("downloadUrl", version.getDownloadurl());
                data.put("version", version.getShortversion());
                data.put("force", version.getMandatory());
                map.put("data", data);
                success = true;
            }
        }
        map.put(SUCCESS, success);
        return map;
    }


    @RequestMapping(value = "addUpdateInfo", method = RequestMethod.POST)
    public String addUpdateInfo(
        @RequestParam(required = true, value = "appType") String appType,
        @RequestParam(required = true, value = "version") String version,
        @RequestParam(required = true, value = "onlineTime") String onlineTime,
        @RequestParam(required = true, value = "size") String size,
        @RequestParam(required = true, value = "md5Code") String md5Code,
        @RequestParam(required = true, value = "serverInfo") String serverInfo,
        @RequestParam(required = true, value = "instructions") String instructions
    ) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("appversion")) {

            AppUpdateInfo appUpdateInfo = new AppUpdateInfo();
            appUpdateInfo.setAppType(Integer.valueOf(appType));
            appUpdateInfo.setVersion(version);
            try {
                appUpdateInfo.setOnlineTime(DateUtils.parseDate(onlineTime, "yyyy-MM-dd"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            appUpdateInfo.setSize(Integer.valueOf(size));
            appUpdateInfo.setMd5Code(md5Code);
            appUpdateInfo.setServerInfo(serverInfo);
            appUpdateInfo.setInstructions(instructions);

            appUpdateVersionService.addUpdateInfo(appUpdateInfo);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

